"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const maishu_node_mvc_1 = require("maishu-node-mvc");
const website_config_1 = require("./website-config");
const typeorm_1 = require("typeorm");
const path = require("path");
const fs = require("fs");
const entities_1 = require("./entities");
class WeiXinDataContext {
    constructor(entityManager) {
        this.entityManager = entityManager;
        this.settings = this.entityManager.getRepository(entities_1.WeiXinSetting);
        this.user = this.entityManager.getRepository(entities_1.User);
    }
}
exports.WeiXinDataContext = WeiXinDataContext;
async function createDataContext(connConfig) {
    let logger = maishu_node_mvc_1.getLogger(`${website_config_1.projectName}:${createDataContext.name}`);
    let connectionManager = typeorm_1.getConnectionManager();
    if (connectionManager.has(connConfig.database) == false) {
        let entitiesPath = path.join(__dirname, "entities.js");
        if (!fs.existsSync(entitiesPath)) {
            logger.error(`Entities path is not exists, path is ${entitiesPath}.`);
        }
        let entities = [entitiesPath];
        let dbOptions = {
            type: "mysql",
            host: connConfig.host,
            port: connConfig.port,
            username: connConfig.user,
            password: connConfig.password,
            database: connConfig.database,
            synchronize: true,
            logging: false,
            connectTimeout: 3000,
            entities,
            name: connConfig.database
        };
        await typeorm_1.createConnection(dbOptions);
    }
    let connection = typeorm_1.getConnection(connConfig.database);
    let dc = new WeiXinDataContext(connection.manager);
    return dc;
}
exports.createDataContext = createDataContext;
